import { BizKfExtraProColumnType } from '@/components';
import * as API from '@/services';
import { Divider, message, Space, Typography } from 'antd';
import { createRespResult, KfModal, KfPagingTablePage, KfPagingTablePagePropsAction, useBackendEnum } from 'kf-web-library';
import React, { useCallback, useRef } from 'react';
import { useAccess, useLocation } from 'umi';
import QuickForm from './components/QuickForm';
import './index.less';
import HxIcon from "@/components/HxIcon";

type Entity = API.AbtLink;
type EntityPageQueryParams = any;
const entityTypeName = '友情链接';
const EntityQuickForm = QuickForm;

interface EntityTableListProps {}

/**
 * 友情链接 列表页面
 */
const EntityTableList: React.FC<EntityTableListProps> = (props) => {
  const location = useLocation();
  const access = useAccess();
  const { enumDict, enumTypeDict, getBackendEnum } = useBackendEnum();
  const actionRef = useRef<KfPagingTablePagePropsAction<Entity, EntityPageQueryParams>>();
  const originalLinks = useRef<API.AbtLink[]>([]);

  const handleDragSortEnd = useCallback((beforeIndex: number, afterIndex: number, newDataSource: API.AbtLink[]) => {
    API.patchSiteAboutInfo({
      toolAddress: newDataSource,
    }).then((resp) => {
      if (resp.flag) {
        actionRef?.current?.setDataSource(newDataSource);
        message.success('修改列表排序成功');
      }
    });
  }, []);

  return (
    <KfPagingTablePage<Entity, EntityPageQueryParams, BizKfExtraProColumnType>
      actionRef={actionRef}
      entityTypeName={entityTypeName}
      drag={{
        dragSortKey: 'sort',
        onDragSortEnd: handleDragSortEnd,
      }}
      pagingQuery={(p) => {
        return new Promise((resolve, reject) => {
          API.querySiteAboutInfo().then((resp) => {
            originalLinks.current = resp.data?.linkAddress || [];
            const links = originalLinks.current
              .filter((ablink) => {
                if (p.searchText) {
                  const { nameEn, nameCn, url } = ablink;
                  return url?.includes(p.searchText) || nameCn?.includes(p.searchText) || nameEn?.includes(p.searchText);
                }
                return true;
              })
              .map((ablink, inx) => {
                return { ...ablink, inx } as Entity;
              });
            const newRespResult = createRespResult(links, resp.flag, {}) as API.RespPageResult<Entity>;
            resolve(newRespResult);
          });
        });
      }}
      opActionsDef={{
        single: {
          deleteOne: (record) => {
            KfModal.deleteConfirm(record.nameCn, () => {
              API.patchSiteAboutInfo({
                linkAddress: originalLinks.current.filter((abtlink, strInx) => strInx !== record.inx)
              }).then((resp) => {
                if (resp.flag) {
                  message.info('删除成功');
                  actionRef.current?.reload();
                }
              });
            });
          },
        },
      }}
      opFloatingsDef={{
        noargs: {
          createModal: {
            show: true,
            buttonText: '新增',
            fltRender: () => ({
              title: `新建`,
              width: 800,
              content: <EntityQuickForm formType={'create'} />,
            }),
          },
        },
        single: {
          modifyModal: (record) => ({
            title: `编辑`,
            width: 800,
            content: <EntityQuickForm formType={'modify'} bizId={record.inx} />,
          }),
        },
      }}
      proTable={{
        rowKey: 'inx',
        pagination: false,
        tableBarActions: (action, rows) => {
          return [];
        },
        search: {
          optionRender: (searchConfig, formProps, dom) => [...dom],
        },
      }}
      columns={[
        {
          title: '关键字',
          dataIndex: 'searchText',
          sorter: false,
          hideInTable: true,
          hideInForm: true,
          fieldProps: {
            placeholder: '名称和编码',
          },
        },
        {
          title: '排序',
          dataIndex: 'sort',
          width: 50,
          className: 'drag-visible',
          hideInSearch: true,
        },
        {
          title: '名称',
          dataIndex: nameof<Entity>((x) => x.nameCn),
          sorter: false,
          hideInSearch: true,
          render: (text, record) => {
            return (
              <div>
                <div><HxIcon type={"hxicon-cn2"}/> {record.nameCn}</div>
                <div><HxIcon type={"hxicon-en2"}/> {record.nameEn}</div>
              </div>
            );
          },
        },
        {
          title: '地址',
          width: 200,
          ellipsis: true,
          dataIndex: nameof<Entity>((x) => x.url),
          hideInSearch: true,
        },
        {
          title: '操作',
          fixed: 'right',
          width: 130,
          dataIndex: 'option',
          valueType: 'option',
          render: (_, record) => (
            <Space size={0} split={<Divider type="vertical" />}>
              <a onClick={() => actionRef.current?.openFloating.single?.modifyModal(record, 'modal')}>编辑</a>
              <a onClick={() => actionRef.current?.executeAction.single?.deleteOne(record)}>
                <Typography.Text type="danger">删除</Typography.Text>
              </a>
            </Space>
          ),
        },
      ]}
    />
  );
};

export default EntityTableList;
